package com.jkt.rms.controller;

import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.jkt.rms.businessservice.RoleBusinessService;

import com.jkt.rms.commons.utils.ServiceLocator;
import com.jkt.rms.vo.SystemRoleLinkupVO;

public class SysRoleLinkupController extends SimpleFormController {
	
	

	private static final Logger LOG = Logger.getLogger(SystemRoleController.class);
	private RoleBusinessService rolelinkupBusinessService = ServiceLocator.getServiceLocator().locate("roleBusinessService");  ;

	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException bindException)
			 throws Exception {
		LOG.debug("inside onSubmit");
		
		String action_type = request.getParameter("action_type");
		if(null!= action_type && action_type.equals("action_submit"))
		{
			// TODO : if validation success then proceed.
			SystemRoleLinkupVO sysrolelinkupvo = (SystemRoleLinkupVO)command;
			rolelinkupBusinessService.saveModulesForRole(sysrolelinkupvo);
		}
		return showForm(request, response, bindException);
	}
	
	@Override
	protected Map<String, SystemRoleLinkupVO> referenceData(HttpServletRequest request, Object command,Errors errors) throws Exception {
		LOG.debug("inside referenceData");
		
		final BindException be = (BindException)errors;
		//int countError = be.getErrorCount();
		
		Map<String, SystemRoleLinkupVO> originalModel = be.getModel();
		SystemRoleLinkupVO sysrolelinkupvo = (SystemRoleLinkupVO)originalModel.get("command");
		
		String action_type = request.getParameter("action_type");
		if(null == action_type){
			sysrolelinkupvo = new SystemRoleLinkupVO();
			sysrolelinkupvo =  rolelinkupBusinessService.findAllLinkupRoles();
			originalModel.put("command", sysrolelinkupvo);

			return originalModel;
		}
		if(action_type.equals("action_select")|| action_type.equals("action_submit") )
		{
			sysrolelinkupvo = rolelinkupBusinessService.findModuleByRole(sysrolelinkupvo);
			originalModel.put("command", sysrolelinkupvo);
		}
		return originalModel;
	}
}